package com.web44.ssm.shiro;

import com.web44.ssm.bean.Adminuser;
import com.web44.ssm.service.IAdminuserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: MyReam
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/19 14:00
 */
public class MyReam extends AuthorizingRealm {

    @Autowired
    private IAdminuserService adminuserService;

    private static Map<String, List<String>> authorizationMap = new HashMap<>();

    static {
        authorizationMap.put("admin", Arrays.asList("emp:add","emp:edit"));
        authorizationMap.put("lpy", Arrays.asList("emp:add","emp:del"));
    }

    /**
     * 认证器
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();

        // 通过用户名获取用户实体
        Adminuser adminuser = adminuserService.queryAdminuserByUsername(username);
        if(adminuser != null) {
            /*
            * Object principal,
            * Object hashedCredentials,
            *  ByteSource credentialsSalt,
            * String realmName
            * */
             // 获取认证信息
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    adminuser.getPassword(),
                    ByteSource.Util.bytes("salt"),
                    this.getName()
            );
            // 没有异常  登录成功 否则就会登录失败
            return info;
        }

        return null;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户名
        String username = principalCollection.getPrimaryPrincipal().toString();
        // 登录用户的权限
        List<String> auths = authorizationMap.get(username);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(auths);
        return info;
    }


}
